package com.thinkgem.jeesite.common.component.redis.service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

public class PPrintListener extends JedisPubSub{

	public PPrintListener(PSubHandler handler) {
	    super();
	    this.handler = handler;
    }

	public PPrintListener(String clientId,Jedis jedis){
		handler = new PSubHandler(clientId,jedis);
	}

	public PPrintListener(Jedis jedis){
		handler = new PSubHandler(jedis);
	}

	public PSubHandler getHandler() {
    	return handler;
    }

	public void setHandler(PSubHandler handler) {
    	this.handler = handler;
    }

	@Override
	public void onMessage(String channel, String message) {
		//此处我们可以取消订阅
		if(message.equalsIgnoreCase("quit")){
			this.unsubscribe(channel);
		}
		handler.handle(channel, message);
	}
	
	@Override
	public void onPMessage(String pattern, String channel, String message) {
		System.out.println("message receive:" + message + ",pattern channel:" + channel);
		
	}

	@Override
	public void onSubscribe(String channel, int subscribedChannels) {
		handler.subscribe(channel);
		System.out.println("subscribe:" + channel + ";total channels : " + subscribedChannels);
		
	}

	@Override
	public void onUnsubscribe(String channel, int subscribedChannels) {
		handler.unsubscribe(channel);
		System.out.println("unsubscribe:" + channel + ";total channels : " + subscribedChannels);
		
	}

	@Override
	public void onPUnsubscribe(String pattern, int subscribedChannels) {
		System.out.println("unsubscribe pattern:" + pattern + ";total channels : " + subscribedChannels);
		
	}

	@Override
	public void onPSubscribe(String pattern, int subscribedChannels) {
		System.out.println("subscribe pattern:" + pattern + ";total channels : " + subscribedChannels);		
	}
	
	@Override
	public void unsubscribe(String... channels) {
        super.unsubscribe(channels);
        for(String channel : channels){
        	handler.unsubscribe(channel);
        }
    }

	private PSubHandler handler;

}
